#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
AI聊天界面组件
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, 
                             QLineEdit, QPushButton, QLabel, QFrame, QScrollArea,
                             QComboBox, QMessageBox, QSplitter)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont, QTextCursor
import sys
import os

# 添加项目根目录到路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ai.deepseek_service import DeepSeekService, AIAnalysisThread


class AIChatWidget(QWidget):
    """AI聊天界面组件"""
    
    def __init__(self, api_key: str, cars_data: list = None):
        super().__init__()
        self.api_key = api_key
        self.cars_data = cars_data or []
        self.deepseek_service = DeepSeekService(api_key)
        self.ai_thread = None
        
        self.init_ui()
        self.setup_connections()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("🤖 AI小圆汽车顾问")
        title_label.setFont(QFont("Microsoft YaHei", 18, QFont.Bold))
        title_label.setStyleSheet("""
            QLabel {
                color: #2c3e50;
                padding: 10px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #667eea, stop:1 #764ba2);
                color: white;
                border-radius: 8px;
                margin-bottom: 10px;
            }
        """)
        title_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(title_label)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        layout.addWidget(splitter)
        
        # 左侧：快速功能区
        left_widget = self.create_quick_actions()
        splitter.addWidget(left_widget)
        
        # 右侧：聊天区域
        right_widget = self.create_chat_area()
        splitter.addWidget(right_widget)
        
        # 设置分割器比例
        splitter.setSizes([300, 500])
        
    def create_quick_actions(self):
        """创建快速功能区"""
        widget = QFrame()
        widget.setStyleSheet("""
            QFrame {
                background-color: #f8f9fa;
                border-radius: 10px;
                border: 1px solid #e9ecef;
            }
        """)
        
        layout = QVBoxLayout(widget)
        layout.setSpacing(10)
        
        # 快速功能标题
        quick_title = QLabel("🚀 快速功能")
        quick_title.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        quick_title.setStyleSheet("color: #495057; margin-bottom: 10px;")
        layout.addWidget(quick_title)
        
        # 数据分析按钮
        self.analyze_btn = QPushButton("📊 智能数据分析")
        self.analyze_btn.setStyleSheet(self.get_button_style("#28a745"))
        layout.addWidget(self.analyze_btn)
        
        # 购车推荐区域
        recommend_label = QLabel("🎯 购车推荐")
        recommend_label.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        recommend_label.setStyleSheet("color: #495057; margin-top: 15px;")
        layout.addWidget(recommend_label)
        
        # 预算输入
        self.budget_input = QLineEdit()
        self.budget_input.setPlaceholderText("预算范围，如：10-15万")
        self.budget_input.setStyleSheet(self.get_input_style())
        layout.addWidget(self.budget_input)
        
        # 偏好输入
        self.preference_input = QLineEdit()
        self.preference_input.setPlaceholderText("偏好，如：省油、空间大、操控好")
        self.preference_input.setStyleSheet(self.get_input_style())
        layout.addWidget(self.preference_input)
        
        # 推荐按钮
        self.recommend_btn = QPushButton("💡 获取推荐")
        self.recommend_btn.setStyleSheet(self.get_button_style("#007bff"))
        layout.addWidget(self.recommend_btn)
        
        # 车型对比区域
        compare_label = QLabel("🔍 车型对比")
        compare_label.setFont(QFont("Microsoft YaHei", 12, QFont.Bold))
        compare_label.setStyleSheet("color: #495057; margin-top: 15px;")
        layout.addWidget(compare_label)
        
        # 车型选择
        self.car_selector = QComboBox()
        self.car_selector.setStyleSheet(self.get_input_style())
        self.update_car_selector()
        layout.addWidget(self.car_selector)
        
        # 对比按钮
        self.compare_btn = QPushButton("⚖️ 对比分析")
        self.compare_btn.setStyleSheet(self.get_button_style("#6f42c1"))
        layout.addWidget(self.compare_btn)
        
        # 添加弹性空间
        layout.addStretch()
        
        return widget
    
    def create_chat_area(self):
        """创建聊天区域"""
        widget = QFrame()
        widget.setStyleSheet("""
            QFrame {
                background-color: white;
                border-radius: 10px;
                border: 1px solid #e9ecef;
            }
        """)
        
        layout = QVBoxLayout(widget)
        layout.setSpacing(10)
        
        # 聊天标题
        chat_title = QLabel("💬 AI对话")
        chat_title.setFont(QFont("Microsoft YaHei", 14, QFont.Bold))
        chat_title.setStyleSheet("color: #495057; margin-bottom: 10px;")
        layout.addWidget(chat_title)
        
        # 聊天显示区域
        self.chat_display = QTextEdit()
        self.chat_display.setReadOnly(True)
        self.chat_display.setStyleSheet("""
            QTextEdit {
                border: 1px solid #dee2e6;
                border-radius: 8px;
                padding: 15px;
                font-size: 14px;
                line-height: 1.6;
                background-color: #ffffff;
            }
        """)
        self.chat_display.setMinimumHeight(300)
        layout.addWidget(self.chat_display)
        
        # 输入区域
        input_layout = QHBoxLayout()
        
        self.message_input = QLineEdit()
        self.message_input.setPlaceholderText("输入您的问题，如：哪款车性价比最高？")
        self.message_input.setStyleSheet(self.get_input_style())
        input_layout.addWidget(self.message_input)
        
        self.send_btn = QPushButton("发送")
        self.send_btn.setStyleSheet(self.get_button_style("#17a2b8"))
        self.send_btn.setFixedWidth(80)
        input_layout.addWidget(self.send_btn)
        
        layout.addLayout(input_layout)
        
        # 添加欢迎消息
        self.add_ai_message("👋 您好！我是AI汽车顾问，可以帮您分析汽车数据、推荐车型、对比车辆。请选择快速功能或直接提问！")
        
        return widget
    
    def get_button_style(self, color):
        """获取按钮样式"""
        return f"""
            QPushButton {{
                background-color: {color};
                color: white;
                border: none;
                padding: 12px 20px;
                border-radius: 6px;
                font-size: 14px;
                font-weight: bold;
                min-height: 20px;
            }}
            QPushButton:hover {{
                background-color: {color}dd;
                transform: translateY(-1px);
            }}
            QPushButton:pressed {{
                background-color: {color}bb;
            }}
            QPushButton:disabled {{
                background-color: #6c757d;
                color: #ffffff;
            }}
        """
    
    def get_input_style(self):
        """获取输入框样式"""
        return """
            QLineEdit, QComboBox {
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 14px;
                background-color: white;
            }
            QLineEdit:focus, QComboBox:focus {
                border-color: #007bff;
                outline: none;
            }
            QComboBox::drop-down {
                border: none;
                width: 20px;
            }
            QComboBox::down-arrow {
                image: none;
                border-left: 5px solid transparent;
                border-right: 5px solid transparent;
                border-top: 5px solid #6c757d;
            }
        """
    
    def setup_connections(self):
        """设置信号连接"""
        self.analyze_btn.clicked.connect(self.analyze_data)
        self.recommend_btn.clicked.connect(self.get_recommendation)
        self.compare_btn.clicked.connect(self.compare_cars)
        self.send_btn.clicked.connect(self.send_message)
        self.message_input.returnPressed.connect(self.send_message)
    
    def update_cars_data(self, cars_data: list):
        """更新汽车数据"""
        self.cars_data = cars_data
        self.update_car_selector()
    
    def update_car_selector(self):
        """更新车型选择器"""
        self.car_selector.clear()
        if self.cars_data:
            for car in self.cars_data[:20]:  # 限制显示前20款
                if isinstance(car, dict):
                    name = car.get('name', '未知')
                else:
                    name = getattr(car, 'name', '未知')
                self.car_selector.addItem(name)
    
    def add_user_message(self, message: str):
        """添加用户消息"""
        self.chat_display.append(f"""
        <div style='text-align: right; margin: 10px 0;'>
            <div style='background: #007bff; color: white; padding: 10px 15px; 
                       border-radius: 15px 15px 5px 15px; display: inline-block; 
                       max-width: 70%; text-align: left;'>
                👤 {message}
            </div>
        </div>
        """)
        self.scroll_to_bottom()
    
    def add_ai_message(self, message: str):
        """添加AI消息"""
        self.chat_display.append(f"""
        <div style='text-align: left; margin: 10px 0;'>
            <div style='background: #f8f9fa; color: #333; padding: 10px 15px; 
                       border-radius: 15px 15px 15px 5px; display: inline-block; 
                       max-width: 80%; border: 1px solid #e9ecef;'>
                🤖 {message.replace(chr(10), '<br>')}
            </div>
        </div>
        """)
        self.scroll_to_bottom()
    
    def scroll_to_bottom(self):
        """滚动到底部"""
        cursor = self.chat_display.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.chat_display.setTextCursor(cursor)
    
    def analyze_data(self):
        """分析数据"""
        if not self.cars_data:
            QMessageBox.warning(self, "⚠️ 提示", "请先获取汽车数据")
            return
        
        self.add_user_message("请分析当前的汽车数据")
        self.add_ai_message("🔄 正在分析数据，请稍候...")
        
        self.set_buttons_enabled(False)
        
        self.ai_thread = AIAnalysisThread(
            self.deepseek_service, 
            "analyze", 
            cars_data=self.cars_data
        )
        self.ai_thread.analysis_completed.connect(self.on_analysis_completed)
        self.ai_thread.error_occurred.connect(self.on_analysis_error)
        self.ai_thread.start()
    
    def get_recommendation(self):
        """获取推荐"""
        budget = self.budget_input.text().strip()
        preferences = self.preference_input.text().strip()
        
        if not budget and not preferences:
            QMessageBox.warning(self, "⚠️ 提示", "请输入预算或偏好信息")
            return
        
        if not self.cars_data:
            QMessageBox.warning(self, "⚠️ 提示", "请先获取汽车数据")
            return
        
        self.add_user_message(f"推荐汽车：预算{budget}，偏好{preferences}")
        self.add_ai_message("🔄 正在为您推荐合适的车型...")
        
        self.set_buttons_enabled(False)
        
        self.ai_thread = AIAnalysisThread(
            self.deepseek_service,
            "recommend",
            budget=budget,
            preferences=preferences,
            cars_data=self.cars_data
        )
        self.ai_thread.analysis_completed.connect(self.on_analysis_completed)
        self.ai_thread.error_occurred.connect(self.on_analysis_error)
        self.ai_thread.start()
    
    def compare_cars(self):
        """对比汽车"""
        if not self.cars_data:
            QMessageBox.warning(self, "⚠️ 提示", "请先获取汽车数据")
            return
        
        selected_car = self.car_selector.currentText()
        if not selected_car:
            QMessageBox.warning(self, "⚠️ 提示", "请选择要对比的车型")
            return
        
        # 简单选择前几款进行对比
        car_names = [selected_car]
        if len(self.cars_data) > 1:
            for car in self.cars_data[:3]:
                name = car.get('name', '') if isinstance(car, dict) else getattr(car, 'name', '')
                if name != selected_car and name not in car_names:
                    car_names.append(name)
        
        self.add_user_message(f"对比车型：{', '.join(car_names)}")
        self.add_ai_message("🔄 正在对比分析车型...")
        
        self.set_buttons_enabled(False)
        
        self.ai_thread = AIAnalysisThread(
            self.deepseek_service,
            "compare",
            car_names=car_names,
            cars_data=self.cars_data
        )
        self.ai_thread.analysis_completed.connect(self.on_analysis_completed)
        self.ai_thread.error_occurred.connect(self.on_analysis_error)
        self.ai_thread.start()
    
    def send_message(self):
        """发送消息"""
        message = self.message_input.text().strip()
        if not message:
            return
        
        self.message_input.clear()
        self.add_user_message(message)
        self.add_ai_message("🔄 正在思考...")
        
        self.set_buttons_enabled(False)
        
        self.ai_thread = AIAnalysisThread(
            self.deepseek_service,
            "analyze",
            cars_data=self.cars_data,
            question=message
        )
        self.ai_thread.analysis_completed.connect(self.on_analysis_completed)
        self.ai_thread.error_occurred.connect(self.on_analysis_error)
        self.ai_thread.start()
    
    def on_analysis_completed(self, result: str):
        """分析完成"""
        # 移除"正在分析"的消息
        self.remove_last_ai_message()
        self.add_ai_message(result)
        self.set_buttons_enabled(True)
    
    def on_analysis_error(self, error: str):
        """分析错误"""
        self.remove_last_ai_message()
        self.add_ai_message(f"❌ {error}")
        self.set_buttons_enabled(True)
    
    def remove_last_ai_message(self):
        """移除最后一条AI消息"""
        content = self.chat_display.toHtml()
        # 简单的方法：重新设置内容，移除最后一条消息
        lines = content.split('<div style=\'text-align: left; margin: 10px 0;\'>')
        if len(lines) > 1:
            content = '<div style=\'text-align: left; margin: 10px 0;\'>'.join(lines[:-1])
            self.chat_display.setHtml(content)
    
    def set_buttons_enabled(self, enabled: bool):
        """设置按钮状态"""
        self.analyze_btn.setEnabled(enabled)
        self.recommend_btn.setEnabled(enabled)
        self.compare_btn.setEnabled(enabled)
        self.send_btn.setEnabled(enabled)
